package com.daxt.controller.index;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.base.common.util.JwtUtil;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.TokenInfo;
import com.daxt.common.result.ResultUtil;
import com.daxt.common.util.HttpWsUtil;
import com.daxt.mapper.sys.DeptMapper;
import com.daxt.mapper.sys.UserDeptMapper;
import com.daxt.mapper.sys.UserMapper;
import com.daxt.model.dic.SystemConfigType;
import com.daxt.model.dic.VersionsMarkType;
import com.daxt.model.service.base.vo.BaseUser;
import com.daxt.model.service.base.vo.Dept;
import com.daxt.model.service.base.vo.UserDept;
import com.daxt.utils.BaseUtil;
import com.daxt.utils.IpUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.Operation;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.mapper.sys.OperationLogMapper;
import com.daxt.model.service.base.param.LoginInfo;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.base.vo.OperationLog;
import com.daxt.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.servlet.ModelAndView;

@Api(tags = "index")
@RestController
public class IndexController {

    @Value(value = "${cas.server-url-prefix}")
    private String serverUrlPrefix = "";

    @Value(value = "${cas.client-host-url}")
    private String clientHostUrl = "";

    @Autowired
    private UserService userService;
    @Autowired
    private OperationLogMapper operationLogMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private DeptMapper deptMapper;

    //注入获取配置文件内容
    @Autowired
    private Environment env;


    @ApiOperation(value = "刷新token", notes = "")
    @GetMapping("/refToken")
    public Result<String> refToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        return userService.refToken(token);
    }

    @ApiOperation(value = "登录", notes = "")
    @PostMapping("/login")
    public Result<UserInfo> login(@RequestBody LoginInfo loginInfo, HttpServletRequest request) {
        if(loginInfo.getUsername().equals("admin")){
            loginInfo.setFrom("ADMIN");
        }else{
            loginInfo.setFrom("WEB");
        }
        String ip=IpUtil.getIP(request);
        Result<UserInfo> login = userService.login(loginInfo, request);
        if (ResultCode.RESULT_SUCCESS.getCode().equals(login.getCode())) {
            //将单点登录的，登录日志单独记录在了 /user/login/log  接口中，用来解决单点登录没有登录日志的问题
            OperationLog entity = new OperationLog();
            entity.setOtype("1");
            entity.setOcontent("登录");
            entity.setOperationBy(loginInfo.getUsername());

            QueryWrapper<BaseUser> queryWrapper=new QueryWrapper();
            queryWrapper.eq("username",loginInfo.getUsername());
            BaseUser baseUser= userMapper.selectOne(queryWrapper);

            String deptName=null;
            String fondsId=null;
            if(baseUser.getDeptIds()!=null){
                QueryWrapper<Dept> queryWrapper2=new QueryWrapper();
                queryWrapper2.eq("id",baseUser.getDeptIds());
                Dept dept= deptMapper.selectOne(queryWrapper2);
                deptName=dept.getDeptName();

                List<Dept> deptList = deptMapper.getAllParentDept(baseUser.getDeptIds());
                if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
                    Long fId= deptList.get(1).getFondsId();
                    if(fId !=null && fId!=0){
                        fondsId=fId.toString();
                    }
                }else{
                    Long fId= deptList.get(0).getFondsId();
                    if(fId !=null && fId!=0){
                        fondsId=fId.toString();
                    }
                }
            }

            entity.setIp(ip);
            entity.setOperationDept(deptName);
            entity.setFondsId(fondsId);
            entity.setCreateTime(LocalDateTime.now());
            operationLogMapper.insert(entity);
        }
        return login;

    }



    @ApiOperation(value = "登出", notes = "")
    @PostMapping("/user/logout")
    public Result<String> logout(HttpServletRequest request) {

        HttpSession session = request.getSession();
        session.invalidate();
        Map m = new HashMap();
        m.put("redirect","redirect:" + serverUrlPrefix + "/logout?service=" + clientHostUrl + "/#/dashboard");
//        m.put("redirect",env.getProperty("cas.server-url-prefix") + "/logout?service=http://127.0.0.1:7502/logoutSuccess");

        JSONObject json = new JSONObject(m);
//        JSONArray jsonArray = new JSONArray();
//        jsonArray.add("redirect",env.getProperty("cas.server-url-prefix") + "/logout?service=http://127.0.0.1:7502/");
        return ResultUtil.success(json.toJSONString());

    }




//    @GetMapping("/checkTicket")
//    public void index(HttpServletRequest request,HttpServletResponse response) throws IOException {
//        //获取sessionid
//        String jsessionid = request.getSession().getId();
//        String token = "";
//
//        //cas
//        AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
//        if(null != principal){
//            Map<String, Object> attributes = principal.getAttributes();
//
//            for (Map.Entry<String, Object> entry : attributes.entrySet()) {
//                String key = entry.getKey();
//                Object val = entry.getValue();
//                System.out.printf("%s:%s\r\n", key, val);
//            }
//            String username = principal.getName();
//            System.out.println("单点登录用户名:" + username);
//            String subject = "SSO";
//
//
//
//            LoginInfo loginInfo = new LoginInfo();
//            loginInfo.setFrom("ADMIN");
//            loginInfo.setUsername(username);
//            loginInfo.setLoginType("2");
//            Result<UserInfo> login = userService.login(loginInfo, request);
//            if(login.getCode().equals(ResultCode.RESULT_SUCCESS.getCode())){
//                UserInfo userInfo = login.getData();
//                token = userInfo.getToken();
//            }
//
//
//
//    }
//
//        // 前端页面地址
//        response.sendRedirect("http://192.168.137.1/#/dashboard?jsessionid=" + jsessionid+"&token="+token);
//    }
    /**
     * 注销
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){
        return "redirect:https://127.0.0.1:8443/cas/logout";
    }


//    @ApiOperation(value = "首页跳转", notes = "")
//    @GetMapping("/index")
//    public ModelAndView index(HttpServletRequest request) {
//        HttpSession session = request.getSession(false);
//        session = request.getSession();
//        System.out.println("sessionId:"+session.getId());
//        Assertion assertion = session != null ? (Assertion) session.getAttribute("_const_cas_assertion_") : null;
//        ModelAndView mv = new ModelAndView("redirect:http://192.168.0.110:7501");
//        return new ModelAndView("redirect:http://192.168.0.110:7501");
//    }

}
